/*****************************
 * Copyright (c) 2008 by snzo Co. Ltd.  All rights reserved.
 ****************************/
package com.core.utils;

import java.io.File;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.opensymphony.xwork2.ActionContext;

/**
 * @{#} FileUtils.java Create on Sep 10, 2008 3:36:05 PM
 * <p>
 * 保存文件类.
 * 路径组合规则.应用的绝对路径+[/o|/s]+应用的域名+/年/月+唯一文件名. 
 * 唯一文件名加上系统时间.
 * </p>
 * @author <a href="mailto:cwx714@hotmail.com">cuiwx</a>
 * @version v 0.1
 */
public class FileUtils {

	private static Logger logger = LoggerFactory.getLogger(FileUtils.class);

	public static final String UPLOAD_FILE_PATH = "/uploads";
	public static final int SMALL_WIDTH = 124;
	public static final int SMALL_HEIGHT = 149;

	/**
	 * 
	 */
	private FileUtils() {

	}

	/**
	 * 返回扩展名.
	 * 
	 * @param fileName
	 * @return ""
	 */
	public static String getExt(String fileName) {
		logger.info("in the getext the file name is :" + fileName);

		if (StringUtils.isBlank(fileName) || fileName.lastIndexOf('.') < 0) {
			return "";
		}
		return fileName == null ? "" : fileName.substring(fileName
				.lastIndexOf('.'));
	}

	/**
	 * 根据用户id返回用户的名字.
	 * 
	 * @param userid
	 * @param filename
	 * @return name
	 */
	public static String getFilePath(String filename) {

		// 取得应用的名称
		String namespace = "/sys";
		if (ActionContext.getContext() != null
				&& ActionContext.getContext().getActionInvocation() != null
				&& ActionContext.getContext().getActionInvocation().getProxy() != null
				&& StringUtils.isNotBlank(ActionContext.getContext()
						.getActionInvocation().getProxy().getNamespace())) {
			namespace = ActionContext.getContext().getActionInvocation()
					.getProxy().getNamespace();
		}

		StringBuffer filepath = new StringBuffer("");
		if (StringUtils.isNotBlank(namespace) && !namespace.equals("/")) {
			filepath.append(namespace).append('/');
		}

		// 加上年月
		filepath.append(new SimpleDateFormat("yyyy/MM").format(new Date()))
				.append('/');

		return filepath.toString();
	}

	/**
	 * 取得文件的唯一名称.
	 * 
	 * @param userid
	 * @param filename
	 * @return ""
	 */
	public static String getFileName(String filename) {
		// 生成唯一文件名
		StringBuffer savefilename = new StringBuffer();
		savefilename.append(
				StringUtils.trim(filename.substring(0, filename
						.lastIndexOf('.')))).append("_").append(new Date().getTime());
		try {
			return MD5.crypt(savefilename.toString());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}

		return "";
	}

	/**
	 * 保存文件.
	 * 
	 * @param file
	 * @param fileName
	 * @return yywr
	 */
	public static String saveFile(File file, String fileName) {
		
		if (file == null) return "";
		
		String webPath = ServletActionContext.getServletContext().getRealPath(
				"/");
		if (webPath.endsWith("/")) {
			webPath = webPath.substring(0, webPath.length() - 1);
		}
		logger.debug("web Path :" + webPath);

		// 保存原始图片.

		String relFilePath = getFilePath(fileName);
		String relFileName = getFileName(fileName);
		String relFileExt = getExt(fileName);

		logger.debug("relFilePath : " + relFilePath);
		logger.debug("relFileName : " + relFileName);
		logger.debug("relFileExt : " + relFileExt);

		StringBuffer storePath = new StringBuffer();
		storePath.append(webPath);
		storePath.append(UPLOAD_FILE_PATH);
		storePath.append(relFilePath);
		
		File tempFile = new File(storePath.toString());
		if (!tempFile.exists()) {
			logger.info("the make dir is run...");
			tempFile.mkdirs();
		}
		storePath.append(relFileName);
		storePath.append(relFileExt);
		logger.info("StorePath:" + storePath.toString());
		try {
			UploadUtils.saveFile(storePath.toString(), file);

		} catch (IOException e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
			return "";
		}

		return new StringBuffer().append(relFilePath).append(relFileName)
				.append(relFileExt).toString();
	}

}
